<?php
namespace frontend\modules\Api\controllers;

use Yii;
/**
 * Class IndustryController
 *
 * @package frontend\modules\Api\controllers
 * @desc 行业管理
 */
class IndustryController extends ApiController
{

    const CACHE_BUCKET = 'industryList';
    const CACHE_TIMEOUT = 7200;
    /**
     * 重载初始化方案
     */
    public function init()
    {
        parent::init();
    }

    /**
     * @throws
     * 获取行业数据列表 并整合成树形菜单形式
     */
    public function actionLists()
    {
        // 先从缓存里尝试命中
        $redis = Yii::$app->get('redis');
        $cacheList = $redis->get(self::CACHE_BUCKET);
        if(!empty($cacheList)) {
            $cacheList = json_decode($cacheList,true);
            return self::successResponse($cacheList);
        }
        // 从DB获取（然后存入缓存）
        // 取出industry行业的数据 并整理成级联样式
        $sql = 'SELECT * FROM `industry` order by `parent_id` ASC';
        $list = Yii::$app->db->createCommand($sql)->queryAll();
        $retList = self::getTreeList($list,0);
        if(!empty($retList)) {
            // 写入缓存
            $redis->setex(self::CACHE_BUCKET,self::CACHE_TIMEOUT,json_encode($retList,JSON_UNESCAPED_UNICODE));
        }
        return self::successResponse($retList);
    }

    /**
     * @param     $data
     * @param     $pid
     * @param int $deep
     *
     * @return array
     * @desc 生成树形菜单
     */
    public static function getTreeList($data,$pid,$deep=0)
    {
        //static $tree=array();
        $tree=[];
        foreach ($data as $row) {
            $row['label'] = $row['name'];
            $row['value'] = $row['id'];
            if($row['parent_id']==$pid){
                $row['deep']=$deep;
                $row['children']= self::getTreeList($data,$row['id'],$deep+1);
                if(empty($row['children'])) unset($row['children']);
                $tree[]=$row;
            }
        }
        return $tree;

    }
}
